<template>
  <el-tabs
    v-model="editableTabsValue"
    type="card"
    class="demo-tabs"
    closable
    @tab-remove="removeTab"
  >
    <el-tab-pane
      v-for="item in editableTabs"
      :key="item.name || ''"
      :label="item.title"
      :name="item.name"
    >
      <slot></slot>
    </el-tab-pane>
  </el-tabs>
</template>

<script lang="ts">
import { ElTabs, ElTabPane } from "element-plus";
import { defineComponent, reactive, toRefs, watch } from "vue";
import { useRoute, useRouter, RouteRecordName } from "vue-router";
export default defineComponent({
  components: {
    ElTabs,
    ElTabPane,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const state: Editable = reactive({
      editableTabs: [],
      editableTabsValue: "",
    });
    interface Tab {
      name: string | RouteRecordName | null | undefined | any;
      title: string | RouteRecordName | null | undefined | any;
    }
    interface Editable {
      editableTabs: Array<Tab>;
      editableTabsValue: string | RouteRecordName | null | undefined | any;
    }

    const removeTab = (targetName: string) => {
      const tabs = state.editableTabs;
      if (tabs.length > 1 && route.fullPath !== "/meter") {
        let activeName = state.editableTabsValue;
        if (activeName === targetName) {
          tabs.forEach((tab: Tab, index: number) => {
            if (tab.name === targetName) {
              const nextTab: Tab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
              }
            }
          });
        }
        state.editableTabsValue = activeName;
        state.editableTabs = tabs.filter((tab: Tab) => tab.name !== targetName);
      }
    };
    const addTabs = () => {
      let isHas = false;
      if (route.fullPath === "/") {
        router.push({ name: "Meter" });
        return;
      }
      const tabs = state.editableTabs,
        len = tabs.length;
      for (let i = 0; i < len; i++) {
        const tab: Tab = tabs[i];
        if (tab.name === route.name) {
          isHas = true;
          break;
        }
      }
      if (!isHas) {
        const newTab: Tab = {
          name: route.name || "",
          title: route.meta.title + "" || "",
        };
        state.editableTabs.push(newTab);
        state.editableTabsValue = newTab.name;
      }
    };

    watch(route, (v) => {
      addTabs();
    });

    if (state.editableTabs.length <= 0) {
      addTabs();
    }

    return {
      addTabs,
      removeTab,
      ...toRefs(state),
    };
  },
  methods: {
    removeTab() {},
    addTabs(): void {
      this.editableTabs.push({
        title: this.$route.meta.title,
        name: this.$route.name,
      });
      this.editableTabsValue = this.$route.name;
    },
  },
});
</script>

<style></style>
